<?php
/**
 * @package		yos_news_crawler
 * @subpackage	Helper
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

require_once(dirname(__FILE__).DS.'phpWebHacks.php');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');

/**
 * YOS Getting images from remote site
 */
class YOS_Get_Image extends JObject 
{	
	function __construct($link_id, $src, $image_path, $max_width = 0, $max_height = 0){
		$this->link_id = $link_id;
		$this->src = $src;
		$this->max_width = $max_width;
		$this->max_height = $max_height;
		
		$this->tmp_path = $image_path;
	}
	
	/**
	 * Get an image then store in tmp directory
	 *
	 * @param string $src full image url
	 * @param int $max_width
	 * @param int $max_height
	 * @return boolean
	 */
	function get_image(){
		//get image
		$browser = new phpWebHacks();
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Get image data BEGIN: ".$this->src);  }
		$response = @$browser->get($this->src);
		if (!$response) {
			$this->setError('[YOS_Get_Image] '.$browser->getErrors());
			return false;
		}
		
		$page_header = $browser->get_head();
		if (!isset($page_header['Status']['Code']) || $page_header['Status']['Code'] != 200) {
			$this->setError('[YOS_Get_Image] Unable to get image: '.$this->src);
			return false;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Get image data END.");  }
		
		//write image to specified location
		//create directoy with name is $link_id in tmp
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Check/Create image folder BEGIN: ".$this->tmp_path);  }
		if(!JFolder::exists($this->tmp_path)){
			if(!JFolder::create($this->tmp_path)){
				$this->setError('[YOS_Get_Image] Cannot create directoy: '.$this->tmp_path);
				return false;
			}
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Check/Create image folder END.");  }
		
		$file_name = JFile::getName($this->src);
		$file_name = $this->_make_safe_file_name($file_name);
		$file_stored = $this->tmp_path.DS.$file_name;
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Write file BEGIN: ".$file_stored);  }
		if(!JFile::write($file_stored, $response)){
			$this->setError('[YOS_Get_Image] Cannot write file: '.$file_stored);
			return false;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Write file END.");  }
		
		//process image file type
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Process image file extension BEGIN: ".$file_name);  }
		$file_name2 = $file_name;
		if(function_exists('exif_imagetype')){
			if($int_image_type = exif_imagetype($file_stored)){
				$str_image_extension = image_type_to_extension($int_image_type, 1);
				//remove current image extension (if exist)
				$file_name2 = JFile::stripExt($file_name);
				//add the real extension
				$file_name2 .= $str_image_extension;
			}
			else {
				//cannot get image type (unknow reason!)
				//TODO: trying to get extension from header
			}
		}
		else{
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(6, "[YOS_Get_Image] exif_imagetype function not found.");  }
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Process image file extension END.");  }

		//process duplicate files
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Check for duplicate, rename BEGIN:");  }
		$file_name2 = $this->_process_duplicate($file_name2, $this->tmp_path);
		
		//rename file
		if ($file_name2 != $file_name) {
			$file_stored2 = $this->tmp_path.DS.$file_name2;
			if(!JFile::move($file_stored, $file_stored2)){
				$this->setError('[YOS_Get_Image] Cannot move file: '.$file_stored.' to new file: '.$file_stored2);
				return false;
			}
			$file_stored = $file_stored2;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Check for duplicate, rename END.");  }
		
		//check if need resize
		if ($this->max_width && $this->max_height) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Resize image BEGIN: ".$file_stored);  }
			require_once(dirname(__FILE__).DS.'ImageResizeFactory.php');
			if(!ImageResizeFactory::getInstanceOf($file_stored, $file_stored, $this->max_width, $this->max_height)){
				$this->setError('[YOS_Get_Image] Cannot resize image: '.$file_stored);
				return false;
			}
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(5, "[YOS_Get_Image] Resize image END.");  }
		}
		
		return $file_stored;
	}
	
	private function _process_duplicate($file_name_in, $str_dir){
		$i = 1;
		$str_name = JFile::stripExt(JFile::getName($file_name_in));
		$str_ext = JFile::getExt($file_name_in);
		$file_name = $str_name.'.'.$str_ext;
		while (JFile::exists($str_dir.DS.$file_name)) {
			$file_name = $str_name.'_'.$i.'.'.$str_ext;
			$i++;
		}
		return $file_name;
	}
	
	/**
	 * Make file name safe to store
	 *
	 * @param string $str_in
	 * @return string
	 */
	private function _make_safe_file_name($str_in){
		$str_out = $str_in;
		
		$str_out = JFile::makeSafe($str_out);
		
		return $str_out;
	}
}
